package com.fqyd.campustransaction.controller;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.fqyd.campustransaction.model.Goods;
import com.fqyd.campustransaction.model.Type;
import com.fqyd.campustransaction.model.User;
import com.fqyd.campustransaction.utils.Tools;

/**
 * 商品
 */
@Controller
@Scope(value = "prototype")
public class GoodsController extends BaseController {

	@RequestMapping("admin_goods_list")
	public String goodsList(HttpServletRequest request) {
		User user = (User) request.getSession().getAttribute("loguser");
		user = userService.getById(user.getId());
		List<Goods> goodsList = goodsService.getByUserId(user.getId());
		List<Type> types = typeService.getAll();
		request.setAttribute("goodsList", goodsList);
		request.setAttribute("types", types);
		return "admin/goods_list";
	}

	@RequestMapping("admin_goods_add")
	public String goodsAdd(HttpServletRequest request, RedirectAttributes attributes) {
		String typeId = request.getParameter("type_id");
		String name = request.getParameter("name");
		String price = request.getParameter("price");
		String description = request.getParameter("description");
		String picture = "/page/static/images/goods/default.png";
		List<Type> types = typeService.getAll();
		request.setAttribute("types", types);
		if (name == null || name.isEmpty()) {
			return "admin/goods_add";
		}
		User user = (User) request.getSession().getAttribute("loguser");
		user = userService.getById(user.getId());
		String goodsId = Tools.createID();
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) (request);
		MultipartFile file = multipartRequest.getFile("file");
		if (!file.getOriginalFilename().isEmpty()) {
			String filePath = request.getServletContext().getRealPath("/") + "page/static/images/goods/";
			String fileName = goodsId + "_" + file.getOriginalFilename();
			File destFile = new File(filePath, fileName);
			try {
				file.transferTo(destFile);
			} catch (IOException e) {
				e.printStackTrace();
			}
			picture = "/page/static/images/goods/" + fileName;
		}
		Goods goods = new Goods();
		goods.setId(goodsId);
		goods.setTypeId(typeId);
		goods.setUserId(user.getId());
		goods.setName(name);
		goods.setPicture(picture);
		goods.setPrice(BigDecimal.valueOf(Double.valueOf(price)));
		goods.setDescription(description);
		goods.setStatus("待审核");
		goodsService.add(goods);
		attributes.addFlashAttribute("message", "操作成功：发布商品（" + goods.getName() + "）成功，等待管理员审核");
		return "redirect:admin_goods_list.do";
	}

	@RequestMapping("admin_goods_modify")
	public String goodsModify(HttpServletRequest request) {
		String goodsId = request.getParameter("goods_id");
		if (Tools.isEmpty(goodsId)) {
			return "redirect:admin_goods_list.do";
		}
		Goods goods = goodsService.getById(goodsId);
		if (goods == null) {
			return "redirect:admin_goods_list.do";
		}
		List<Type> types = typeService.getAll();
		request.setAttribute("types", types);
		request.setAttribute("goods", goods);
		return "admin/goods_modify";
	}

	//Du:搜索商品
	@RequestMapping("admin_goods_search")
	public String goods(HttpServletRequest request) {
		User user = (User) request.getSession().getAttribute("loguser");//从Session中获取用户对象
		String userId = user.getId();//提取用户ID
		String name = request.getParameter("goodsName");//从前台请求中获取商品名称
		name = "%" + name + "%";//为数据库模糊查询更改格式
		Goods goods = new Goods();
		goods.setUserId(userId);
		goods.setName(name);
		List<Goods> goodsList = goodsService.getByUserAndOrderId(goods);//查询对应用户的商品并返回
		List<Type> types = typeService.getAll();
		request.setAttribute("goodsList", goodsList);
		request.setAttribute("types", types);
		return "admin/goods_list";
	}

	//Du:删除商品
	@RequestMapping("admin_goods_delete")
	public String goodsDelete(HttpServletRequest request, RedirectAttributes attributes) {
		String goodsId = request.getParameter("goods_id");//从前台接收商品ID
		if (Tools.isEmpty(goodsId)) {//如果接收的商品ID为空则返回刷新页面
			return "redirect:admin_goods_list.do";
		}
		Goods goods = goodsService.getById(goodsId);//从数据库中根据商品ID查询商品
		if (goods == null) {//如果数据库中无此商品则返回刷新页面
			return "redirect:admin_goods_list.do";
		}
		if(!goods.getStatus().equals("已出售")){//如果商品正在交易则不可删除
			goods.setStatus("已删除");//删除商品
			goodsService.update(goods);
			attributes.addFlashAttribute("message", "操作成功：删除商品成功");
		}
		return "redirect:admin_goods_list.do";
	}

	@RequestMapping("admin_goods_modify_save")
	public String goodsModifySave(HttpServletRequest request, RedirectAttributes attributes) {
		String goodsId = request.getParameter("goods_id");
		String typeId = request.getParameter("type_id");
		String name = request.getParameter("name");
		String price = request.getParameter("price");
		String description = request.getParameter("description");
		if (Tools.isEmpty(goodsId)) {
			return "redirect:admin_goods_list.do";
		}
		Goods goods = goodsService.getById(goodsId);
		if (goods == null) {
			return "redirect:admin_goods_list.do";
		}
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) (request);
		MultipartFile file = multipartRequest.getFile("file");
		if (!file.getOriginalFilename().isEmpty()) {
			String filePath = request.getServletContext().getRealPath("/") + "page/static/images/goods/";
			String fileName = goodsId + "_" + file.getOriginalFilename();
			File destFile = new File(filePath, fileName);
			try {
				file.transferTo(destFile);
			} catch (IOException e) {
				e.printStackTrace();
			}
			goods.setPicture(filePath + fileName);
		}
		if ("审核驳回".equals(goods.getStatus())) {
			goods.setStatus("待审核");
		}
		goods.setTypeId(typeId);
		goods.setName(name);
		goods.setPrice(BigDecimal.valueOf(Double.valueOf(price)));
		goods.setDescription(description);
		goodsService.update(goods);
		attributes.addFlashAttribute("message", "操作成功：修改商品（" + goods.getName() + "）成功");
		return "redirect:admin_goods_list.do";
	}
}
